package cn.ytr.project.service.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import cn.ytr.project.domain.Product;
import cn.ytr.project.mapper.ProductMapper;
import cn.ytr.project.query.PageResult;
import cn.ytr.project.query.QueryObject;
import cn.ytr.project.service.IProductService;
import cn.ytr.project.util.MybatisUtil;

public class ProductServiceImpl implements IProductService {


	@Override
	public void save(Product product) {
		SqlSession session = MybatisUtil.getSession();
		ProductMapper productMapper = session.getMapper(ProductMapper.class);
		productMapper.save(product);
		session.commit();
		session.close();
	}

	@Override
	public void delete(Long id) {
		SqlSession session = MybatisUtil.getSession();
		ProductMapper productMapper = session.getMapper(ProductMapper.class);
		productMapper.delete(id);
		session.commit();
		session.close();
	}

	@Override
	public void update(Product product) {
		SqlSession session = MybatisUtil.getSession();
		ProductMapper productMapper = session.getMapper(ProductMapper.class);
		productMapper.update(product);
		session.commit();
		session.close();
	}

	@Override
	public Product get(Long id) {
		SqlSession session = MybatisUtil.getSession();
		ProductMapper productMapper = session.getMapper(ProductMapper.class);
		Product product = productMapper.get(id);
		session.close();
		return product;
	}

	@Override
	public List<Product> listAll() {
		SqlSession session = MybatisUtil.getSession();
		ProductMapper productMapper = session.getMapper(ProductMapper.class);
		List<Product> all = productMapper.listAll();
		session.close();
		return all;
	}

	@Override
	public PageResult query(QueryObject queryObject) {
		SqlSession session = MybatisUtil.getSession();
		ProductMapper productMapper = session.getMapper(ProductMapper.class);
		//查询总条数
		int totalCount = productMapper.queryForCount(queryObject);
		//如果总条数为0,不在执行下面的查询
		if(totalCount == 0){
			return new PageResult(queryObject.getPageSize());
		}
		//查询结果集
		List<Product> list = productMapper.queryForList(queryObject);
		//封装PageResult对象
		session.close();
		return new PageResult(queryObject.getCurrentPage(), totalCount,
				list, queryObject.getPageSize());
	}

}
